
// Definition for a binary tree node.
function TreeNode(val, left, right) {
    this.val = (val===undefined ? 0 : val)
    this.left = (left===undefined ? null : left)
    this.right = (right===undefined ? null : right)
}

/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var findMode = function(root) {
  if(!root) return [];
  let map = new Map();
  function preView(node) {
    if(!node) return;
    if(map.has(node.val)) {
      map.set(node.val, map.get(node.val) + 1);
    } else {
      map.set(node.val, 1);
    }
    preView(node.left);
    preView(node.right);
  }
  preView(root);
  let arr = [...map];
  arr = arr.sort((a, b) => b[1] - a[1]);
  let num = arr[0][1], result = [];
  for(let i = 0; i < arr.length; i++) {
    if(arr[i][1] < num) break;
    result.push(arr[i][0]);
  }
  return result;
};
